from utils.getui_utils import getui_utils
from utils.time_util import current_time


class client_parse:
    getui = getui_utils()
    mTimeLenth = 1200  # 20分钟
    lastTime = 0
    bollLastTime = 0  # 布林穿中线通知

    def checkNotice(self, resonate, deviate, support, currentParice, continuity, bollinger, bollingerCenterArr):
        """
        resonate：共振、  deviate：背离、  support：阻力、 continuity：连续性、  bollinger：布林
        """

        self.bollAlert(bollingerCenterArr[0], bollingerCenterArr[1], bollingerCenterArr[2], bollingerCenterArr[3])

        mSupportArr = self.defaultValue(support, split=0)
        mResonateDict = self.defaultValue(resonate)
        mDeviateDict = self.defaultValue(deviate)
        mContinuityDict = self.defaultValue(continuity)
        mBollingerDict = self.defaultValue(bollinger)

        mImportantDict, mImportantOrder = self.levelImportant(resonateDict=mResonateDict, bollingerDict=mBollingerDict,
                                                              continuityDict=mContinuityDict,
                                                              supportArr=mSupportArr, currentParice=currentParice)
        mNormalDict, mNormalOrder = self.levelNormal(resonateDict=mResonateDict, bollingerDict=mBollingerDict,
                                                     continuityDict=mContinuityDict,
                                                     supportArr=mSupportArr, currentParice=currentParice)
        mSlightDict, mSlightOrder = self.levelSlight(resonateDict=mResonateDict, bollingerDict=mBollingerDict,
                                                     continuityDict=mContinuityDict,
                                                     supportArr=mSupportArr, currentParice=currentParice)

        if mImportantDict["alert"] != 0 or mImportantDict["support"] != "无":
            return mImportantDict, mImportantOrder

        if mNormalDict["alert"] != 0 or mNormalDict["support"] != "无":
            return mNormalDict, mNormalOrder

        if mSlightDict["alert"] != 0 or mSlightDict["support"] != "无":
            return mSlightDict, mSlightOrder

        if self.continuityStatus(mContinuityDict, 1):
            nextSupport = self.nearSupport(mSupportArr, currentParice, 1)
            return {"alert": 0, "support": nextSupport}, None

        if self.continuityStatus(mContinuityDict, 2):
            nextSupport = self.nearSupport(mSupportArr, currentParice, 2)
            return {"alert": 0, "support": nextSupport}
        return {"alert": 0, "support": "无"}, None

    def bollAlert(self, centor15, centor30, centor60, centor240):
        """
        布林穿中线提醒
        """

        if self.bollCalculateTime():
            if centor15 == 1:
                self.bollNotice("15分钟图表上穿布林线")
                return

            if centor30 == 1:
                self.bollNotice("30分钟图表上穿布林线")
                return

            if centor60 == 1:
                self.bollNotice("1小时图表上穿布林线")
                return

            if centor240 == 1:
                self.bollNotice("4小时图表上穿布林线")
                return

            if centor15 == 2:
                self.bollNotice("15分钟图表下穿布林线")
                return

            if centor30 == 2:
                self.bollNotice("30分钟图表下穿布林线")
                return

            if centor60 == 2:
                self.bollNotice("1小时图表下穿布林线")
                return

            if centor240 == 2:
                self.bollNotice("4小时图表下穿布林线")
                return

    def levelImportant(self, resonateDict, bollingerDict, continuityDict, supportArr, currentParice):
        """
        一级警报
        resonateDict：共振、 supportArr：阻力、 continuityDict：连续性、  bollingerDict：布林
        """

        if self.keyInDict("长线", "中线", "短线", dict=resonateDict) and self.keyInDict("15分钟", "30分钟", "60分钟",
                                                                                  dict=bollingerDict):

            if resonateDict["长线"] == "共振下跌" and resonateDict["短线"] == "共振下跌" and resonateDict["中线"] == "共振下跌":
                supports = self.nearSupport(supportArr, currentParice, 1)
                if self.continuityStatus(continuityDict, 1):
                    if bollingerDict["30分钟"] == "下跌" or bollingerDict["60分钟"] == "下跌":
                        if self.calculateTime():
                            self.notice(1)
                            return {"alert": 1, "support": supports}, 2
                return {"alert": 0, "support": supports}, None

            if resonateDict["长线"] == "共振上涨" and resonateDict["短线"] == "共振上涨" and resonateDict["中线"] == "共振上涨":
                supports = self.nearSupport(supportArr, currentParice, 2)
                if self.continuityStatus(continuityDict, 2):
                    if bollingerDict["30分钟"] == "上涨" or bollingerDict["60分钟"] == "上涨":
                        if self.calculateTime():
                            self.notice(1)
                            return {"alert": 1, "support": supports}, 1
                return {"alert": 0, "support": supports}, None
        return {"alert": 0, "support": "无"}, None

    def levelNormal(self, resonateDict, bollingerDict, continuityDict, supportArr, currentParice):
        """
        二级警报
        resonateDict：共振、 supportArr：阻力、 continuityDict：连续性、  bollingerDict：布林
        """

        if self.keyInDict("中线", "短线", dict=resonateDict) and self.keyInDict("15分钟", "30分钟", dict=bollingerDict):
            if resonateDict["短线"] == "共振下跌" and resonateDict["中线"] == "共振下跌":
                supports = self.nearSupport(supportArr, currentParice, 1)
                if self.continuityStatus(continuityDict, 1):
                    if bollingerDict["30分钟"] == "下跌":
                        if self.calculateTime():
                            self.notice(2)
                            return {"alert": 2, "support": supports}, 2
                return {"alert": 0, "support": supports}, None

            if resonateDict["短线"] == "共振上涨" and resonateDict["中线"] == "共振上涨":
                supports = self.nearSupport(supportArr, currentParice, 2)
                if self.continuityStatus(continuityDict, 2):
                    if bollingerDict["30分钟"] == "上涨":
                        if self.calculateTime():
                            self.notice(2)
                            return {"alert": 2, "support": supports}, 1
                return {"alert": 0, "support": supports}, None
        return {"alert": 0, "support": "无"}, None

    def levelSlight(self, resonateDict, bollingerDict, continuityDict, supportArr, currentParice):
        """
        三级警报
        resonateDict：共振、 supportArr：阻力、 continuityDict：连续性、  bollingerDict：布林
        """

        if self.keyInDict("短线", dict=resonateDict) and self.keyInDict("15分钟", dict=bollingerDict):
            if resonateDict["短线"] == "共振下跌":
                supports = self.nearSupport(supportArr, currentParice, 1)
                if self.continuityStatus(continuityDict, 1):
                    if bollingerDict["15分钟"] == "下跌":
                        if self.calculateTime():
                            self.notice(3)
                            return {"alert": 3, "support": supports}, 2
                return {"alert": 0, "support": supports}, None

            if resonateDict["短线"] == "共振上涨":
                supports = self.nearSupport(supportArr, currentParice, 2)
                if self.continuityStatus(continuityDict, 2):
                    if bollingerDict["15分钟"] == "上涨":
                        if self.calculateTime():
                            self.notice(3)
                            return {"alert": 3, "support": supports}, 1
                return {"alert": 0, "support": supports}, None
        return {"alert": 0, "support": "无"}, None

    def keyInDict(self, *args, dict, type=1):
        """
        判断字典是否存在key
        args：数组key、 dict：字典、    type=1：and     type=2：of
        """

        if dict is not None:
            for i in range(len(args)):
                if type == 2:
                    if args[i] in dict:
                        return True
                    if i == len(args) - 1:
                        return False

                if type == 1:
                    if args[i] not in dict:
                        return False

                    if i == len(args) - 1:
                        return True
        return False

    def defaultValue(self, value, split=1):
        """
        初始值
        """

        if value is not None and value != "无":
            if split == 0:
                return value
            return self.stringToMap(value)
        return None

    def bollNotice(self, status):
        """
        布林线状态
        """
        self.getui.pushMsg("交易预警", status, voice="")

    def notice(self, level):
        """
        发送通知
        """

        if level == 1:
            self.getui.pushMsg(title="交易预警", body="一级预警已触发", voice="first.wav")

        if level == 2:
            self.getui.pushMsg(title="交易预警", body="二级预警已触发", voice="second.wav")

        if level == 3:
            self.getui.pushMsg(title="交易预警", body="三级预警已触发", voice="third.wav")

    def bollCalculateTime(self):
        '''
        布林时间计算
        '''

        if self.bollLastTime != 0:
            if current_time() - self.bollLastTime >= self.mTimeLenth:
                self.bollLastTime = current_time()
                return True
        else:
            self.bollLastTime = current_time()
            return True
        return False

    def calculateTime(self):
        '''
        时间计算
        '''

        if self.lastTime != 0:
            if current_time() - self.lastTime >= self.mTimeLenth:
                self.lastTime = current_time()
                return True
        else:
            self.lastTime = current_time()
            return True
        return False

    def stringToMap(self, value):
        '''
        字符串转字典
        '''

        if value is None and value == "无":
            return "无"

        valueDice = {}
        valueArr = value.split(";")
        for item in valueArr:
            if item != "":
                itemValue = item.split(":")
            valueDice[itemValue[0]] = itemValue[1]
        return valueDice

    def continuityStatus(self, array, status):
        '''
        k线连续涨跌幅
        status=1：下跌      status=2：上涨
        '''

        if array is not None:
            if status == 1:
                if ("15分钟" in array and -0.1 >= self.stringToNumber(array["15分钟"])) or (
                        "30分钟" in array and -0.15 >= self.stringToNumber(array["30分钟"])) or (
                        "60分钟" in array and -0.2 >= self.stringToNumber(array["60分钟"])):
                    return True

            if status == 2:
                if ("15分钟" in array and self.stringToNumber(array["15分钟"]) >= 0.1) or (
                        "30分钟" in array and self.stringToNumber(array["30分钟"]) >= 0.15) or (
                        "60分钟" in array and self.stringToNumber(array["60分钟"]) >= 0.2):
                    return True
        return False

    def stringToNumber(self, value):
        '''
        百分比string转float
        '''

        if value is not None:
            return float(str(value).replace("%", ""))
        return ""

    def nearSupport(self, supportArray, mCurrentPrice, status):
        '''
        离当前价格较近的阻力位
        status=1：下跌      status=2：上涨
        '''

        if supportArray is not None:
            mCurrent = float(mCurrentPrice)
            for index in range(0, len(supportArray)):
                if supportArray[index] != "" and index != len(supportArray) - 1:
                    if supportArray[index + 1] != "":
                        if float(supportArray[index]) > mCurrent > float(supportArray[index + 1]):
                            if status == 1:
                                return supportArray[index + 1]

                            if status == 2:
                                return supportArray[index]
        return ""
